package com.arvinclub.web.controller.error;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 异常统一捕获和输出
 */
@ControllerAdvice
public class ErrorController {

    /**
     * 所有异常都在这被捕获
     */
    @ExceptionHandler(Throwable.class)
    public String exceptionHandler(Throwable e, Model model) {
        String title = null;
        String msg = null;
        switch (e.getClass().getSimpleName()) {
            case "NoHandlerFoundException":
                title = "请求的页面不存在";
                msg = "404 NOT FOUND";
                break;
            case "HttpRequestMethodNotSupportedException":
                title = "请求的方法不支持";
                break;
            case "NullPointerException":
                title = "请求的资源不存在";
                msg = "java.lang.NullPointerException";
                break;
            case "NumberFormatException":
                title = "非法的数字格式化";
                break;
        }
        model.addAttribute("title", title == null ? e.getClass().getSimpleName() : title);
        model.addAttribute("trace", e.getStackTrace());
        model.addAttribute("msg", msg == null ? e.getMessage() : msg);
        return "error";
    }
}
